/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameheartv2;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 *
 * @author GaoXteen
 */
public class GameStateTableCard extends GameState {

    static BufferedImage img;
    static public int start = 149;
    BufferedImage img1;
    public int topCard;
    public static Vector<Card> vCard;
    public static Vector<Card> handCard;
    public static Vector<Card> selectedCards;
    public JTextField tfChat;
    public static JTextArea tfShowMessage;
    public JScrollPane messagePanel;
    public int viTri = 1;
    public static int trangThai = 3;
    public static Client client;
    public boolean first = true;
    public boolean start1 = true;
    static public JButton midButton;
    static public JTextField player1Core;
    static public JTextField player2Core;
    static public JTextField player3Core;
    static public JTextField player4Core;
    static public JTextField player1Name;
    static public JTextField player2Name;
    static public JTextField player3Name;
    static public JTextField player4Name;
    static public JButton face1Label;
    //public static JPanel image1Pane  = new JPanel();
    static public JButton face2Label;
    //public static JPanel image2Pane  = new JPanel();
    static public JButton face3Label;
    //public static JPanel image3Pane  = new JPanel();
    static public JButton face4Label;
    //public static JPanel image4Pane  = new JPanel();
    static public JButton player1Cards;
    static public JButton player2Cards;
    static public JButton player3Cards;
    static public JButton player4Cards;
    public JButton btGui;
    static public Vector<Player> vTablePlayer;
    public int currPlayer = 0;
    static public Vector<Card> realCards = new Vector<Card>();

    public GameStateTableCard(GameStateFrame _mainGame) {
        viTri = 0;
        this.mainGame = _mainGame;
        selectedCards = new Vector<Card>();

        this.client.tableCard = this;

        this.GAME_STATE = GameDef.STATE_TABLECARD;
        this.width = 811;
        this.height = 634;
        this.topCard = 14;
        vTablePlayer = new Vector<Player>();
        vCard = new Vector<Card>();
        for (int type = 1; type <= 4; type++) {
            for (int i = 0; i < 13; ++i) {

                Card card = new Card(i, type);
                card.addMouseListener(new MyMouseListener());
                card.setActionCommand(Integer.toString(i));
                //  mainGame.vButtonCard.add(card);
                vCard.add(card);
            }
        }
    }

    @Override
    public void MessageEnter(int message) {
        try {
            String fileName = System.getProperty("user.dir") + "\\src\\Resources\\bg2.jpg";
            GameStateTableCard.img = ImageIO.read(new File(fileName));
        } catch (IOException e) {
        }

        mainGame.addKeyListener(new MyKeyListener());
        mainGame.setSize(width, height);
        mainGame.bgJPane.setBounds(0, 0, 816, 639);

        //client= new Client(mainGame.ip, 8999);
        //client.send("26 "+this.viTri);
        for (int type = 1; type <= 4; type++) {
            for (int i = 0; i < 13; ++i) {

                Card card = new Card(i, type);
                card.addMouseListener(new MyMouseListener());
                card.setActionCommand(Integer.toString(i));
                mainGame.vButtonCard.add(card);
                //vCard.add(card);
            }
        }
        tfChat = new JTextField();
        tfChat.setBounds(575, 580, 175, 25);
        tfChat.addActionListener(new MyActionListener());
        tfShowMessage = new JTextArea();
        tfShowMessage.setLineWrap(true);
        tfShowMessage.setWrapStyleWord(true);
        tfShowMessage.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));

        messagePanel = new JScrollPane(tfShowMessage);
        messagePanel.setBounds(575, 505, 215, 73);

        mainGame.getLayeredPane().add(tfChat, new Integer(14));
        mainGame.getLayeredPane().add(messagePanel, new Integer(14));

        player1Core = new JTextField();
        player1Core.setBounds(470, 510, 80, 20);
        player1Core.setText("0");
        Color co = new Color(177, 195, 77);
        player1Core.setBackground(co);
        player1Core.setEditable(false);
        mainGame.getLayeredPane().add(player1Core, new Integer(14));

        player1Name = new JTextField();
        player1Name.setBounds(310, 510, 80, 20);
        player1Name.setBackground(co);
        player1Name.setEditable(false);
        mainGame.getLayeredPane().add(player1Name, new Integer(14));

        player2Core = new JTextField();
        player2Core.setBounds(80, 360, 80, 20);
        player2Core.setBackground(co);
        player2Core.setText("0");
        player2Core.setEditable(false);
        mainGame.getLayeredPane().add(player2Core, new Integer(14));

        player2Name = new JTextField();
        player2Name.setBounds(80, 260, 80, 20);
        player2Name.setBackground(co);
        player2Name.setEditable(false);
        mainGame.getLayeredPane().add(player2Name, new Integer(14));

        player3Core = new JTextField();
        player3Core.setBounds(310, 80, 80, 20);
        player3Core.setBackground(co);
        player3Core.setText("0");
        player3Core.setEditable(false);
        mainGame.getLayeredPane().add(player3Core, new Integer(14));

        player3Name = new JTextField();
        player3Name.setBounds(470, 80, 80, 20);
        player3Name.setBackground(co);
        player3Name.setEditable(false);
        mainGame.getLayeredPane().add(player3Name, new Integer(14));

        player4Core = new JTextField();
        player4Core.setBounds(695, 260, 80, 20);
        player4Core.setBackground(co);
        player4Core.setText("0");
        player4Core.setEditable(false);
        mainGame.getLayeredPane().add(player4Core, new Integer(14));

        player4Name = new JTextField();
        player4Name.setBounds(695, 360, 80, 20);
        player4Name.setBackground(co);
        player4Name.setEditable(false);
        mainGame.getLayeredPane().add(player4Name, new Integer(14));

        String face = mainGame.player.imagePath;
        File file = new File(face);
        ImageIcon icon = new ImageIcon();
        try {
            BufferedImage myPicture = ImageIO.read(file);
            icon = new ImageIcon(myPicture);
        } catch (Exception ex) {
        }

        face1Label = new JButton();
        face1Label.setBackground(co);
        face1Label.setBounds(410, 510, 40, 40);
        face1Label.setBackground(co);
        mainGame.getLayeredPane().add(face1Label, new Integer(4));


        face2Label = new JButton();
        face2Label.setBackground(co);
        //face2Label.setIcon(icon);
        face2Label.setBounds(98, 300, 40, 40);
        face2Label.setBackground(co);
        mainGame.getLayeredPane().add(face2Label, new Integer(4));

        face3Label = new JButton();
        face3Label.setBackground(co);
        face3Label.setBounds(408, 80, 40, 40);
        face3Label.setBackground(co);
        mainGame.getLayeredPane().add(face3Label, new Integer(4));

        face4Label = new JButton();
        face4Label.setBackground(co);
        //face4Label.setIcon(icon);
        face4Label.setBounds(711, 300, 40, 40);
        face4Label.setBackground(co);
        mainGame.getLayeredPane().add(face4Label, new Integer(4));

        String path = System.getProperty("user.dir") + "\\src\\Resources\\gui.jpg";
        btGui = new JButton();
        btGui.setBounds(751, 578, 54, 26);
        btGui.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
        icon = new ImageIcon(path);
        btGui.setIcon(icon);
        btGui.addMouseListener(new GuiMouseListener());
        mainGame.getLayeredPane().add(btGui, new Integer(15));

        String pathCards = System.getProperty("user.dir") + "\\src\\Resources\\back.png";
        midButton = new JButton();
        midButton.setBounds(400, 290, 64, 64);
        midButton.setOpaque(false);
        midButton.setBorderPainted(false);
        midButton.setContentAreaFilled(false);
        midButton.setIcon(new ImageIcon(pathCards));
        midButton.addMouseListener(new MidButtonMouseListener());
        mainGame.getLayeredPane().add(midButton, new Integer(14));
        midButton.setVisible(false);
    }

    @Override
    public void MessageUpdate(int message) {
//            if(this.trangThai == 3 && first ==true )
//            {
//
//                first = false;
//            }

        if (this.trangThai == 2 && first == true) {
            for (int i = 0; i < GameStateTableCard.realCards.size(); i++) {
                GameStateTableCard.realCards.elementAt(i).setVisible(false);
            }
            GameStateTableCard.realCards.clear();
            for (int i = 0; i < GameStateTableCard.vCard.size(); i++) {
                if (GameStateTableCard.vCard.elementAt(i).isUse) {
                    GameStateTableCard.realCards.add(GameStateTableCard.vCard.elementAt(i));
                    int stt = GameStateTableCard.realCards.size() - 1;
                    GameStateTableCard.realCards.elementAt(stt).setBounds((550 - 20 * stt), 423, 57, 74);
                    // mainGame.getLayeredPane().add(  GameStateTableCard.realCards.elementAt(stt),topCard);
                    // topCard++;
                }
            }
            Card.SapTangDan(GameStateTableCard.realCards);
            for (int i = 0; i < GameStateTableCard.realCards.size(); i++) {
                GameStateTableCard.realCards.elementAt(i).setBounds((550 - 20 * i), 423, 57, 74);
                mainGame.getLayeredPane().add(GameStateTableCard.realCards.elementAt(i), i);
                GameStateTableCard.realCards.elementAt(i).setVisible(true);
            }
            first = false;
        }
        if (GameStateTableCard.vTablePlayer.size() == 0) {
            this.client.send("26 " + this.viTri);
        }
        if (GameStateTableCard.vTablePlayer.size() != this.currPlayer) {
            for (int i = 0; i < GameStateTableCard.vTablePlayer.size(); i++) {
                int vitri = vTablePlayer.elementAt(i).vitri;
                String face = GameDef.FacePath + vTablePlayer.elementAt(i).imagePath;
                String name = vTablePlayer.elementAt(i).name;
                File file = new File(face);
                ImageIcon icon = new ImageIcon();
                try {
                    BufferedImage myPicture = ImageIO.read(file);


                    icon = new ImageIcon(myPicture);
                } catch (Exception ex) {
                }
                switch (vitri) {
                    case 1:
                        face1Label.setIcon(icon);
                        player1Name.setText(name);
                        break;
                    case 2:
                        face2Label.setIcon(icon);
                        player2Name.setText(name);
                        break;
                    case 3:
                        face3Label.setIcon(icon);
                        player3Name.setText(name);
                        break;
                    case 4:
                        face4Label.setIcon(icon);
                        player4Name.setText(name);
                        break;
                }
            }

            this.currPlayer = vTablePlayer.size();

        }
        if (start >= 224 && this.start1 == true) {
            this.start1 = false;
            String pathCards = System.getProperty("user.dir") + "\\src\\Resources\\left\\13.png";
            player2Cards = new JButton();
            player2Cards.setOpaque(false);
            player2Cards.setBorderPainted(false);
            player2Cards.setContentAreaFilled(false);
            player2Cards.setIcon(new ImageIcon(pathCards));
            player2Cards.setBounds(161, 254, 67, 142);
            mainGame.getLayeredPane().add(player2Cards, new Integer(14));

            pathCards = System.getProperty("user.dir") + "\\src\\Resources\\top\\13.png";
            player3Cards = new JButton();
            player3Cards.setOpaque(false);
            player3Cards.setBorderPainted(false);
            player3Cards.setContentAreaFilled(false);
            player3Cards.setIcon(new ImageIcon(pathCards));
            player3Cards.setBounds(355, 135, 145, 68);
            mainGame.getLayeredPane().add(player3Cards, new Integer(14));

            pathCards = System.getProperty("user.dir") + "\\src\\Resources\\right\\13.png";
            player4Cards = new JButton();
            player4Cards.setOpaque(false);
            player4Cards.setBorderPainted(false);
            player4Cards.setContentAreaFilled(false);
            player4Cards.setIcon(new ImageIcon(pathCards));
            player4Cards.setBounds(628, 256, 69, 146);
            mainGame.getLayeredPane().add(player4Cards, new Integer(14));

//                 for(int type=1;type<=4;type++)
//                 {
//                    for(int i =0;i<13;++i)
//                    {
//
//                            Card card = new Card (i,type);
//                            card.addMouseListener(new MyMouseListener() );
//                            card.setActionCommand(Integer.toString(i));
//                            mainGame.vButtonCard.add(card);
//                            vCard.add(card);
//                        }
//                    }

        }
    }

    @Override
    public void MessagePaint(int message) {
        this.gameRender();
        mainGame.update(mainGame.getGraphics());
    }

    public void gameRender() {
        // if (mainGame.dbImage == null){
        mainGame.dbImage = mainGame.createImage(width, height);
        if (mainGame.dbImage == null) {
            System.out.println("dbImage is null");
            return;
        } else {
            gp2d = mainGame.dbImage.getGraphics();
        }
        // }

        gp2d.drawImage(GameStateTableCard.img, 0, 0, null);
        String path = System.getProperty("user.dir") + "\\src\\Resources\\start_"
                + Integer.toString(start) + ".png";

        try {
            img1 = ImageIO.read(new File(path));
        } catch (IOException e) {
        }

        gp2d.drawImage(img1, 150, 130, null);
        if (trangThai == 4) {
            if (this.start < 225) {
                this.start += 1;

                if (this.start == 224) {
                    String sourcePath = System.getProperty("user.dir") + "\\src\\voice\\GroupCard.wav";
                    new AePlayWave(sourcePath).start();
                    trangThai = 1;
                    midButton.setVisible(true);
                    for (int i = 0; i < GameStateTableCard.vCard.size(); i++) {
                        if (GameStateTableCard.vCard.elementAt(i).isUse) {
                            GameStateTableCard.realCards.add(GameStateTableCard.vCard.elementAt(i));
                            int stt = GameStateTableCard.realCards.size() - 1;
                            GameStateTableCard.realCards.elementAt(stt).setBounds((550 - 20 * stt), 423, 57, 74);
                            mainGame.getLayeredPane().add(GameStateTableCard.realCards.elementAt(stt), topCard);
                            topCard++;
                        }
                    }
                }
            }

            if (156 <= this.start && this.start <= 218) {
                String sourcePath = System.getProperty("user.dir") + "\\src\\voice\\CardSelected.wav";
                new AePlayWave(sourcePath).start();
            }
        }
    }

    class MyMouseListener implements MouseListener {

        public void mouseClicked(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
            Card selectedCard = (Card) e.getComponent();
            switch (trangThai) {
                case 1:
                    if (423 == selectedCard.getY()) {
                        selectedCard.setBounds(selectedCard.getX(), selectedCard.getY() - 20, selectedCard.getWidth(), selectedCard.getHeight());
                        GameStateTableCard.selectedCards.add(selectedCard);

                    } else {

                        selectedCard.setBounds(selectedCard.getX(), selectedCard.getY() + 20, selectedCard.getWidth(), selectedCard.getHeight());
                        GameStateTableCard.selectedCards.remove(selectedCard);
                        selectedCards.remove(selectedCard);
                    }
                    break;
                case 2:
                    //LQH
//              selectedCard.setBounds(400, 340, 57, 74);
//              mainGame.getLayeredPane().setLayer(e.getComponent(),topCard );
//              String sourcePath = System.getProperty("user.dir")+"\\src\\voice\\DealCard.wav";
//              new AePlayWave(sourcePath).start();
//              topCard ++;
//              client.send("7 "+selectedCard.number+" "+selectedCard.type+" "+viTri);
//              System.out.println("7 "+selectedCard.number+" "+selectedCard.type+" "+viTri);
//              break;
                    //VA
                    int opponentCardType = client.type;
                    selectedCard = (Card) e.getComponent();
                    int heart = 4;
                    Boolean heartBroken = false;
                    boolean haiNhep = KiemTra2Nhep();
                    if (haiNhep == true) {
                        client.startPlayer = viTri;
                        client.currentPlayer = client.startPlayer;
                    }

                    if (client.currentPlayer + 1 == viTri) {
                        //Kiem tra xem minh co phai nguoi dau tien hay ko, neu ko thì phai danh theo type cua thang dau tien
                        if (client.startPlayer + 1 != viTri) {
                            Boolean typeExisted = false;

                            //Kiem tra xem co con nao cung type trong bo bai hay ko
                            for (int i = 0; i < client.baiDuocChia.length; i++) {
                                String[] temp = client.baiDuocChia[i].split(" ");
                                int myType = Integer.parseInt(temp[1]);

                                if (myType == opponentCardType) {
                                    typeExisted = true;
                                    break;
                                }
                            }

                            //neu co con bai cung type trong tay thi phai chon nhung con cung type do
                            if (typeExisted == true) {
                                if (selectedCard.type == opponentCardType) {
                                    e.getComponent().setBounds(400, 340, 57, 74);
                                    DanhBai(selectedCard);
                                }
                            } //neu ko co con nao cung type trong tay thi chon con nao cung dc
                            else {
                                //kiem tra xem co phai tat ca bai trong tay la heart hay ko
                                int heartCount = DemHeart();

                                if ((selectedCard.type == heart && heartBroken == true) || selectedCard.type != heart || heartCount == client.baiDuocChia.length) {
                                    e.getComponent().setBounds(400, 340, 57, 74);
                                    DanhBai(selectedCard);

                                    //danh dau quan bai da duoc xuat ra
                                    DanhDau(selectedCard);
                                }
                            }
                        } // Neu minh la nguoi dau tien thi chon con bai bat ki
                        else {
                            //kiem tra xem co phai tat ca bai trong tay la heart hay ko
                            int heartCount = DemHeart();


                            if (haiNhep == true && 0 == selectedCard.number && 1 == selectedCard.type) {
                                e.getComponent().setBounds(400, 340, 57, 74);
                                DanhBai(selectedCard);

                                //danh dau quan bai da duoc xuat ra
                                DanhDau(selectedCard);
                            } else if ((selectedCard.type == heart && heartBroken == true) || selectedCard.type != heart || heartCount == client.baiDuocChia.length) {
                                e.getComponent().setBounds(400, 340, 57, 74);
                                DanhBai(selectedCard);

                                //danh dau quan bai da duoc xuat ra
                                DanhDau(selectedCard);
                            }
                        }
                    }
                    break;
            }
        }

        public boolean KiemTra2Nhep() {
            boolean result = false;
            for (int i = 0; i < client.baiDuocChia.length; i++) {
                if (client.baiDuocChia[i].compareTo("0 1") == 0) {
                    result = true;
                    break;
                }
            }
            return result;
        }

        public void DanhBai(Card selectedCard) {
            mainGame.getLayeredPane().setLayer(selectedCard, topCard);
            String sourcePath = System.getProperty("user.dir") + "\\src\\voice\\DealCard.wav";
            new AePlayWave(sourcePath).start();
            topCard++;
            client.send("7 " + selectedCard.number + " " + selectedCard.type + " " + viTri);
        }

        public void DanhDau(Card selectedCard) {
            for (int i = 0; i < client.baiDuocChia.length; i++) {
                String[] temp = client.baiDuocChia[i].split(" ");
                int myType = Integer.parseInt(temp[1]);
                int myNum = Integer.parseInt(temp[0]);

                if (myType == selectedCard.type && myNum == selectedCard.number) {
                    client.baiDuocChia[i] = "";
                }
            }
        }

        public int DemHeart() {
            int heartCount = 0;
            int heart = 4;

            for (int i = 0; i < client.baiDuocChia.length; i++) {
                if (client.baiDuocChia[i].compareTo("") != 0) {
                    String[] temp = client.baiDuocChia[i].split(" ");
                    int myType = Integer.parseInt(temp[1]);

                    if (myType == heart) {
                        heartCount++;
                    }
                }
            }

            return heartCount;
        }

        public void mouseReleased(MouseEvent e) {
            if (9 == trangThai) {
                MouseListener mm = e.getComponent().getMouseListeners()[0];
                e.getComponent().removeMouseListener(mm);
            }

        }
    }

    class GuiMouseListener implements MouseListener {

        public void mouseClicked(MouseEvent e) {
            String message = tfChat.getText();
            if (message != null) {
                if (message.trim() != "") {
                    client.send("11 " + mainGame.player.name + " " + message);
                    tfChat.setText("");
                }
            }
        }

        public void mouseEntered(MouseEvent e) {
            String path = System.getProperty("user.dir") + "\\src\\Resources\\send_duel.jpg";
            ImageIcon icon = new ImageIcon(path);
            btGui.setIcon(icon);
        }

        public void mouseExited(MouseEvent e) {
            String path = System.getProperty("user.dir") + "\\src\\Resources\\gui.jpg";
            ImageIcon icon = new ImageIcon(path);
            btGui.setIcon(icon);
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    }

    class MidButtonMouseListener implements MouseListener {

        public void mouseClicked(MouseEvent e) {
            if (GameStateTableCard.trangThai == 3) {
                GameStateTableCard.trangThai = 2;

            }
            String sentMsg = "15 " + viTri + " " + client.soTran + " ";
            if (3 == selectedCards.size()) {
                for (int i = 0; i < 3; i++) {
                    sentMsg = sentMsg + selectedCards.elementAt(i).number + " " + selectedCards.elementAt(i).type + " ";
                }
                client.send(sentMsg);
                e.getComponent().setVisible(false);
            }
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    }

    class MyActionListener implements ActionListener {

        public void actionPerformed(ActionEvent evt) {
            String message = tfChat.getText();
            if (message != null) {
                if (message.trim() != "") {
                    client.send("11 " + mainGame.player.name + " " + message);
                    tfChat.setText("");
                }
            }
        }
    }

    public class MyKeyListener implements KeyListener {

        public void keyPressed(KeyEvent e) {
            int codeKey = e.getKeyCode();
            if (codeKey == e.VK_F1) {
                System.out.println("f1");
            }
        }

        public void keyTyped(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
        }
        //------------------------------------------------------------------

        private void KeyProceed(KeyEvent e) {
        }
    }
}
